package com.atguigu.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.atguigu.constant.RedisConstant;
import com.atguigu.dao.SetmealDao;
import com.atguigu.entity.PageResult;
import com.atguigu.pojo.Setmeal;
import com.atguigu.service.SetmealService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.JedisPool;

import java.util.HashMap;
import java.util.Map;

@Service(interfaceClass = SetmealService.class )
@Transactional
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    SetmealDao setmealDao;
    @Autowired
    JedisPool jedisPool;

    @Override
    public void add(Setmeal setmeal, Integer[] travelgroupIds) {
        //新增套餐
        setmealDao.add(setmeal);//主键回填操作
        //绑定套餐和跟团游的多对多关系
        setSetmealAndTravelGroup(setmeal.getId(), travelgroupIds);
        //将图片保存到Redis
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, setmeal.getImg());

    }


    private void setSetmealAndTravelGroup(Integer setmealId, Integer[] travelgroupIds) {
        if (travelgroupIds!=null && travelgroupIds.length>0) {
            for (Integer travelGroupId : travelgroupIds) {
                setmealDao.setSetmealAndTravelGroup(setmealId, travelGroupId);
                //
               /* Map<String, Integer> map = new HashMap<>();
                map.put("travelgroup_id", travelGroupId);
                map.put("setmeal_id", setmealId);
                setmealDao.setSetmealAndTravelGroup(map);*/
            }
        }
    }
    @Override
    public PageResult findPage(Integer currentPage, Integer pageSize, String queryString) {
       //分页
        PageHelper.startPage(currentPage,pageSize);
        Page page =setmealDao.findPage(queryString);
        return new PageResult(page.getTotal(), page.getResult());
    }

}
